package com.bdqn.controller;

import com.bdqn.mapper.Constants;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysUserService;
import com.bdqn.util.PageSupport;
import com.bdqn.web.converter.BaseController;
import com.mysql.cj.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.io.File;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController extends BaseController {
    private Logger logger = Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;
    private SysRoleService sysRoleService;


    /**
     * 跳转到用户登录页面
     */
    @RequestMapping("/toLogin")
    public String login() {
        return "login";
    }


    @RequestMapping("/login")
    public String doLogin(@RequestParam("account") String account, @RequestParam("password") String password,
                          HttpServletRequest request, HttpSession session) throws Exception {
        logger.debug("进入登录方法");
        // 调用service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account, password);
        if (null != sysUser) {// 登录成功
            // 将登陆用户放入session
            session.setAttribute(Constants.USER_SESSION, sysUser);
            return "redirect:/user/toMain";
        } else {
            // 页面跳转（login.jsp）带出提示信息--转发
            request.setAttribute("error", "用户名或密码错误！");
            return "login";
        }
    }

    @RequestMapping("/toMain")
    public String toMain(HttpSession session) {
        if (session.getAttribute(Constants.USER_SESSION) == null) {
            return "redirect:/sys/user/toLogin";
        }
        return "frame";
    }
    @GetMapping(value = "/toAdd")
    public String toAdd(HttpServletRequest request) {
        return "sysUser/add";
    }

    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest request) {
        System.out.println("捕获到异常" + e.getMessage());
        request.setAttribute("e", e);
        return "sysError";
    }

    @RequestMapping("/exLogin")
    public String exLogin(@RequestParam String account, @RequestParam String password) throws Exception {
        System.out.println(account + password);
        SysUser user = sysUserService.login(account, password);
        if (user != null) {
            throw new RuntimeException("用户名或密码不正确，跳转到错误页面！");
        }
        return "redirect:/user/toMain";
    }

    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId, @RequestParam(defaultValue = "1") Integer pageIndex) {
        List<SysUser> userList = null;
        try {
            // 设置页面容量
            int pageSiz = Constants.pageSize;
            System.out.println("queryRealName" + queryRealName + "queryRoleId" + queryRoleId);
            // 总数量（表）
            int totalCount = sysUserService.getUserCount(queryRealName == null ? null : queryRealName, queryRoleId == null ? 0 : queryRoleId);
            // 总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPage(pageIndex);
            pages.setNumberPage(pageSiz);
            pages.setTotalPage(totalCount);
            int totalPageCount = pages.getTotalPage();
            // 控制首页和尾页
            if (pageIndex > totalPageCount) {
                pageIndex = totalCount;
                throw new RuntimeException("页面不正确");
            }
            userList = sysUserService.getUserList(queryRealName, queryRoleId == null ? 0 : queryRoleId, pageIndex, pageSiz);
            model.addAttribute("userList", userList);
            List<SysRole> roleList = sysRoleService.getRoleList();
            model.addAttribute("roleList", roleList);
            model.addAttribute("queryRealName", queryRealName);
            model.addAttribute("queryRoleId", queryRoleId);
            model.addAttribute("totalPageCount", totalPageCount);
            model.addAttribute("totalCount", totalCount);
            model.addAttribute("currentPageNo", pageIndex);
        } catch (Exception e) {
            logger.error("查询用户列表失败", e);
            return "redirect:/user/toSysError";
        }
        return "sysUser/list";
    }

    /**
     * 跳转到异常处理页面
     *
     * @return
     */
    @RequestMapping(value = "/toSysError")
    public String sysError() {
        return "sysError";
    }

    @PostMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest session) {
        SysUser create = (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreatedUserId(create.getId());
        if (sysUserService.add(sysUser)) {
            return "redirect:/sysUser/list";
        } else {
            return "redirect:/sysUser/toAdd";
        }
    }

    @GetMapping("/view/{id}")
    public String userview(@PathVariable Integer id, Model model) {
        logger.debug("根据id查询用户信息：" + id);
        SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    @GetMapping("toUpdate")
    public String toUpdate(@RequestParam Integer uid, Model model) {
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = sysUserService.getUserById(uid);
        model.addAttribute("sysUser", sysUser);
        return "sysUser/update";
    }

    @PostMapping("/update")
    public String modifySave(SysUser user, HttpSession session) {
        user.setUpdatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.update(user)) {
            return "redirect:/sysUser/list";
        } else {
            return "sysUser/update";
        }
    }

    /**
     * 跳转到添加用户页面
     *
     * @param sysUser
     * @return
     */
    @GetMapping("/add")
    public String toAdd(@ModelAttribute("sysUser") SysUser sysUser) {
        return "sysUser/add";
    }

    /**
     * 添加用户
     *
     * @param sysUser
     * @param session
     * @return
     */
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session) {
        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.add(sysUser)) {
            return "redirect:/sysUser/list";
        } else {
            return "sysUser/add";
        }
    }

    /**
     * 完成对新增用户信息的保存操作
     */
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) {
        String idPicPath = null;
        String workPicPath = null;
        String errorinfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("uploadFile path ==============>" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorinfo = "uploadFileError";
                } else if (i == 1) {
                    errorinfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("uploadFile oldFileName ==============>" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                logger.debug("uploadFile prefix============>" + prefix);
                int filesize = 500000;
                logger.debug("uploadFile size============>" + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过500k
                    request.setAttribute(errorinfo, "*上传大小不得超过 500k");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "Personal.jpg";
                    logger.debug("new fileName========" + attach.getName());
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorinfo, "* 上传失败!");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.debug("idPicPath:" + idPicPath);
                    logger.debug("workPicPath:" + workPicPath);
                } else {
                    request.setAttribute(errorinfo, "*上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag) {
            sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            sysUser.setPicPath(idPicPath);
            sysUser. (workPicPath);
            if (sysUserService.add(sysUser)) {
                return "redirect:/user/list";
            }
        }
        return "sysUser/add";
    }

    @GetMapping("/userExist")
    public Object userExist(@RequestParam String account) {
        logger.debug("验证用户名 account =" + account + "的用户是否存在");
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isNullOrEmpty(account)) {
            resultMap.put("exist", 1);
        } else {
            SysUser sysUser = sysUserService.getAccountExist(account);
            if (sysUser != null) {
                resultMap.put("exist", 1);
            } else
                resultMap.put("exist", 0);
        }
        return null;
    }

    @GetMapping(value = "/{id}/view")
    @ResponseBody
    public Object view(@PathVariable String id) {
        logger.info("根据id查询用户信息id：" + id + "  |");
        SysUser user = null;
        if (id == null || id.equals("")) {
            return "nodata";
        } else {
            try {
                SysUser sysUser = sysUserService.getUserById(id);
                logger.info("用户信息转换为JSON格式：" + user + "   |");
            } catch (Exception e) {
                e.printStackTrace();
                return "failed";
            }
            return user;
        }
    }


}
